<?php
class Install_model extends CI_Model {

    function __construct() {
        parent::__construct();
        $this->load->database();
        $this->load->dbforge();
    }

    function install() {
        if (mysql_num_rows(mysql_query("SHOW TABLES LIKE 'pr_category'")) == 0)
            $this->db->query("CREATE TABLE pr_category(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, category VARCHAR(100) NOT NULL UNIQUE, deadline INT NOT NULL)");
        if (mysql_num_rows(mysql_query("SHOW TABLES LIKE 'pr_college'")) == 0)
            $this->db->query("CREATE TABLE pr_college(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(100) NOT NULL UNIQUE)");
        if (mysql_num_rows(mysql_query("SHOW TABLES LIKE 'pr_level'")) == 0)
            $this->db->query("CREATE TABLE pr_level(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, level INT NOT NULL, name VARCHAR(20) NOT NULL)");
        if (mysql_num_rows(mysql_query("SHOW TABLES LIKE 'pr_rates'")) == 0)
            $this->db->query("CREATE TABLE pr_rates(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, pid INT NOT NULL, ip VARCHAR(40) NOT NULL, category INT NOT NULL)");
        if (mysql_num_rows(mysql_query("SHOW TABLES LIKE 'pr_users'")) == 0)
            $this->db->query("CREATE TABLE pr_users(uid INT NOT NULL PRIMARY KEY AUTO_INCREMENT, username VARCHAR(45) NOT NULL UNIQUE, password VARCHAR(50) NOT NULL, level INT NOT NULL )");
        if (mysql_num_rows(mysql_query("SHOW TABLES LIKE 'pr_works'")) == 0)
            $this->db->query("CREATE TABLE pr_works(pid INT NOT NULL PRIMARY KEY AUTO_INCREMENT, title VARCHAR(100) NOT NULL, content TEXT, realname VARCHAR(20) NOT NULL, studentnum VARCHAR(20) NOT NULL, college INT NOT NULL, filename TEXT NOT NULL, category INT NOT NULL)");
        $query1 = $this->db->get_where('pr_level',array('level' => 1, 'name' => '普通用户'));
        $query2 = $this->db->get_where('pr_level',array('level' => 5, 'name' => '管理员'));
        $query3 = $this->db->get_where('pr_level',array('level' => 99, 'name' => '超级管理员'));
        if ($query1->num_rows() == 0)
            $this->db->query("INSERT INTO pr_level(level, name) VALUES (1, '普通用户')");
        if ($query2->num_rows() == 0)
            $this->db->query("INSERT INTO pr_level(level, name) VALUES (5, '管理员')");
        if ($query3->num_rows() == 0)
            $this->db->query("INSERT INTO pr_level(level, name) VALUES (99, '超级管理员')");

        $this->username = $this->input->post('username');
        $this->password = $this->input->post('password');
        $this->level = 99;

        $query4 = $this->db->get_where('pr_users',array('username' => $this->input->post('username')));
        if ($query4->num_rows() == 0) {
            $this->db->insert('pr_users', $this);
            return TRUE;
        } else {
            return FALSE;
        }
    }
}